// JWT Parser 渲染器
window.JWTParserRenderer = class JWTParserRenderer {
    static getHTML() {
        return `
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-3xl font-bold text-gray-800">JWT 解析工具</h2>
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-500">
                        <span id="jwt-status" class="font-medium">就绪</span>
                    </div>
                </div>
            </div>

            <!-- 工具栏 -->
            <div class="bg-gray-50 border rounded-lg p-4 mb-6">
                <div class="flex flex-wrap items-center gap-3">
                    <button id="parse-jwt" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="key" class="w-4 h-4 mr-2"></i>
                        解析 JWT
                    </button>
                    <button id="copy-jwt-result" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center" disabled>
                        <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                        复制结果
                    </button>
                    <button id="clear-jwt" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                        清空
                    </button>
                    <button id="paste-jwt" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="clipboard" class="w-4 h-4 mr-2"></i>
                        粘贴
                    </button>
                </div>
            </div>

            <!-- 内容区域 -->
            <div class="grid md:grid-cols-2 gap-6">
                <!-- 输入区域 -->
                <div>
                    <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                        <i data-feather="edit-3" class="w-5 h-5 mr-2"></i>
                        JWT Token
                    </h3>
                    <textarea id="jwt-input" class="w-full h-48 p-4 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm" placeholder="请输入JWT token，例如：&#10;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"></textarea>
                    <div class="mt-2 text-sm text-gray-500">
                        字符数: <span id="jwt-input-count">0</span>
                    </div>
                </div>

                <!-- 输出区域 -->
                <div>
                    <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                        <i data-feather="code" class="w-5 h-5 mr-2"></i>
                        解析结果
                    </h3>
                    <div id="jwt-output" class="w-full h-48 p-4 bg-gray-50 border border-gray-300 rounded-lg font-mono text-sm overflow-auto"></div>
                    
                    <!-- Token 状态信息 -->
                    <div id="jwt-token-info" class="mt-4 text-sm text-gray-600 hidden">
                        <div class="grid grid-cols-2 gap-4">
                            <div>算法: <span id="token-algorithm" class="font-medium"></span></div>
                            <div>类型: <span id="token-type" class="font-medium"></span></div>
                            <div class="col-span-2">
                                <div class="flex items-center">
                                    状态: <span id="token-status" class="font-medium ml-1"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Token 详细信息 -->
            <div id="jwt-details" class="mt-6 hidden">
                <div class="grid md:grid-cols-2 gap-6">
                    <!-- Header -->
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                            <i data-feather="settings" class="w-5 h-5 mr-2"></i>
                            Header (头部)
                        </h3>
                        <pre id="jwt-header" class="bg-white p-3 rounded border text-sm font-mono overflow-x-auto"></pre>
                    </div>

                    <!-- Payload -->
                    <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                        <h3 class="text-lg font-semibold text-green-800 mb-3 flex items-center">
                            <i data-feather="package" class="w-5 h-5 mr-2"></i>
                            Payload (载荷)
                        </h3>
                        <pre id="jwt-payload" class="bg-white p-3 rounded border text-sm font-mono overflow-x-auto"></pre>
                    </div>

                    <!-- Signature -->
                    <div class="bg-purple-50 border border-purple-200 rounded-lg p-4">
                        <h3 class="text-lg font-semibold text-purple-800 mb-3 flex items-center">
                            <i data-feather="shield" class="w-5 h-5 mr-2"></i>
                            Signature (签名)
                        </h3>
                        <div id="jwt-signature" class="bg-white p-3 rounded border text-sm font-mono break-all"></div>
                    </div>

                    <!-- Claims -->
                    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                        <h3 class="text-lg font-semibold text-yellow-800 mb-3 flex items-center">
                            <i data-feather="calendar" class="w-5 h-5 mr-2"></i>
                            标准声明
                        </h3>
                        <div id="jwt-claims" class="space-y-2 text-sm"></div>
                    </div>
                </div>
            </div>

            <!-- 使用说明 -->
            <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-4 mt-6">
                <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                    <i data-feather="help-circle" class="w-5 h-5 mr-2"></i>
                    使用说明
                </h3>
                <div class="grid md:grid-cols-2 gap-4 text-sm text-blue-700">
                    <div>
                        <h4 class="font-semibold mb-2">JWT 结构</h4>
                        <ul class="space-y-1">
                            <li>• Header: 包含算法和令牌类型</li>
                            <li>• Payload: 包含声明（claims）</li>
                            <li>• Signature: 验证令牌完整性</li>
                            <li>• 格式: header.payload.signature</li>
                        </ul>
                    </div>
                    <div>
                        <h4 class="font-semibold mb-2">标准声明</h4>
                        <ul class="space-y-1">
                            <li>• iss: 令牌签发者</li>
                            <li>• sub: 令牌主题</li>
                            <li>• aud: 令牌接收者</li>
                            <li>• exp: 过期时间</li>
                            <li>• iat: 签发时间</li>
                            <li>• nbf: 生效时间</li>
                        </ul>
                    </div>
                </div>
                <div class="mt-4 p-3 bg-yellow-100 border border-yellow-300 rounded text-xs text-yellow-800">
                    <strong>注意：</strong> 此工具仅解析JWT结构，不验证签名。生产环境请使用适当的JWT库进行验证。
                </div>
            </div>
        `;
    }

    static init() {
        const jwtInput = document.getElementById('jwt-input');
        const jwtOutput = document.getElementById('jwt-output');
        const parseBtn = document.getElementById('parse-jwt');
        const copyBtn = document.getElementById('copy-jwt-result');
        const clearBtn = document.getElementById('clear-jwt');
        const pasteBtn = document.getElementById('paste-jwt');
        
        // 状态显示
        const statusSpan = document.getElementById('jwt-status');
        const tokenInfo = document.getElementById('jwt-token-info');
        const jwtDetails = document.getElementById('jwt-details');
        
        // 详细信息元素
        const jwtHeader = document.getElementById('jwt-header');
        const jwtPayload = document.getElementById('jwt-payload');
        const jwtSignature = document.getElementById('jwt-signature');
        const jwtClaims = document.getElementById('jwt-claims');
        const tokenAlgorithm = document.getElementById('token-algorithm');
        const tokenType = document.getElementById('token-type');
        const tokenStatus = document.getElementById('token-status');

        let currentResult = '';

        // 更新状态显示
        const updateStatus = (status) => {
            statusSpan.textContent = status;
        };

        // 字符计数
        const updateCharCount = () => {
            document.getElementById('jwt-input-count').textContent = jwtInput.value.length;
        };

        // 解析JWT
        const parseJWT = () => {
            const token = jwtInput.value.trim();
            
            if (!token) {
                DevToolsUtils.showToast('请输入JWT token', 'error');
                return;
            }

            DevToolsUtils.addLoading(parseBtn);
            updateStatus('解析中...');

            setTimeout(() => {
                try {
                    const result = JWTParser.parse(token);
                    
                    if (result.success) {
                        displayJWTResult(result.data);
                        currentResult = JSON.stringify(result.data, null, 2);
                        copyBtn.disabled = false;
                        updateStatus('解析完成');
                        DevToolsUtils.showToast('JWT 解析成功！');
                    } else {
                        jwtOutput.textContent = `解析失败: ${result.error}`;
                        hideJWTDetails();
                        DevToolsUtils.showToast(result.error, 'error');
                        updateStatus('解析失败');
                    }
                } catch (error) {
                    jwtOutput.textContent = `解析错误: ${error.message}`;
                    hideJWTDetails();
                    DevToolsUtils.showToast('JWT 格式无效', 'error');
                    updateStatus('解析失败');
                }
                
                DevToolsUtils.removeLoading(parseBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        };

        // 显示JWT解析结果
        const displayJWTResult = (data) => {
            // 显示基本信息
            jwtOutput.textContent = JSON.stringify({
                header: data.header,
                payload: data.payload,
                signature: data.signature
            }, null, 2);

            // 显示token信息
            tokenAlgorithm.textContent = data.header.alg || 'Unknown';
            tokenType.textContent = data.header.typ || 'Unknown';
            
            // 显示token状态
            const now = Math.floor(Date.now() / 1000);
            let status = '';
            let statusClass = '';
            
            if (data.payload.exp) {
                if (data.payload.exp < now) {
                    status = '已过期';
                    statusClass = 'text-red-600';
                } else {
                    const timeLeft = data.payload.exp - now;
                    if (timeLeft < 3600) { // 小于1小时
                        status = '即将过期';
                        statusClass = 'text-yellow-600';
                    } else {
                        status = '有效';
                        statusClass = 'text-green-600';
                    }
                }
            } else {
                status = '永不过期';
                statusClass = 'text-blue-600';
            }
            
            tokenStatus.textContent = status;
            tokenStatus.className = `font-medium ml-1 ${statusClass}`;
            tokenInfo.classList.remove('hidden');

            // 显示详细信息
            jwtHeader.textContent = JSON.stringify(data.header, null, 2);
            jwtPayload.textContent = JSON.stringify(data.payload, null, 2);
            jwtSignature.textContent = data.signature;

            // 显示标准声明
            displayJWTClaims(data.payload);
            
            jwtDetails.classList.remove('hidden');
        };

        // 显示JWT标准声明
        const displayJWTClaims = (payload) => {
            const claimsMap = {
                'iss': '签发者 (Issuer)',
                'sub': '主题 (Subject)',
                'aud': '接收者 (Audience)',
                'exp': '过期时间 (Expiration)',
                'iat': '签发时间 (Issued At)',
                'nbf': '生效时间 (Not Before)',
                'jti': 'JWT ID'
            };

            let claimsHTML = '';
            
            Object.keys(claimsMap).forEach(claim => {
                if (payload[claim] !== undefined) {
                    let value = payload[claim];
                    
                    // 格式化时间戳
                    if (['exp', 'iat', 'nbf'].includes(claim) && typeof value === 'number') {
                        const date = new Date(value * 1000);
                        value = `${value} (${date.toLocaleString('zh-CN')})`;
                    }
                    
                    claimsHTML += `
                        <div class="flex justify-between">
                            <span class="font-medium">${claimsMap[claim]}:</span>
                            <span class="text-gray-600 text-right flex-1 ml-2 break-all">${value}</span>
                        </div>
                    `;
                }
            });

            if (claimsHTML) {
                jwtClaims.innerHTML = claimsHTML;
            } else {
                jwtClaims.innerHTML = '<div class="text-gray-500">无标准声明</div>';
            }
        };

        // 隐藏JWT详细信息
        const hideJWTDetails = () => {
            tokenInfo.classList.add('hidden');
            jwtDetails.classList.add('hidden');
        };

        // 清空内容
        const clearAll = () => {
            jwtInput.value = '';
            jwtOutput.textContent = '';
            currentResult = '';
            hideJWTDetails();
            copyBtn.disabled = true;
            updateCharCount();
            updateStatus('就绪');
        };

        // 复制结果
        const copyResult = async () => {
            if (currentResult) {
                await DevToolsUtils.copyToClipboard(currentResult);
                DevToolsUtils.showToast('已复制到剪贴板！');
            } else {
                DevToolsUtils.showToast('没有可复制的内容', 'error');
            }
        };

        // 粘贴内容
        const pasteContent = async () => {
            try {
                const text = await navigator.clipboard.readText();
                jwtInput.value = text;
                updateCharCount();
                DevToolsUtils.showToast('粘贴成功！');
            } catch (err) {
                DevToolsUtils.showToast('粘贴失败，请手动粘贴', 'error');
            }
        };

        // 事件监听器
        jwtInput.addEventListener('input', DevToolsUtils.debounce(() => {
            updateCharCount();
            updateStatus('输入中...');
            
            // 实时验证JWT格式
            if (jwtInput.value.trim()) {
                const parts = jwtInput.value.trim().split('.');
                if (parts.length === 3) {
                    updateStatus('格式正确');
                    DevToolsUtils.removeStatusBorder(jwtInput);
                } else {
                    updateStatus('格式错误');
                    DevToolsUtils.addErrorBorder(jwtInput);
                }
            } else {
                updateStatus('就绪');
                DevToolsUtils.removeStatusBorder(jwtInput);
            }
        }, 300));

        parseBtn.addEventListener('click', parseJWT);
        copyBtn.addEventListener('click', copyResult);
        clearBtn.addEventListener('click', clearAll);
        pasteBtn.addEventListener('click', pasteContent);

        // 快捷键支持
        jwtInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && e.ctrlKey) {
                parseJWT();
            }
        });

        // 初始化
        updateCharCount();
        updateStatus('就绪');
        
        // 初始化 Feather 图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
};